<?php
namespace App\Http\Controllers\Wechat;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Repos\OrderRepo;
use App\Repos\UserAddressRepo;
use App\Repos\UserCouponRepo;
use App\Http\Requests\Api\OrderRequest;


class RechargeController extends Controller
{
    public function makeOrder(OrderRequest $request)
    {
    	$rs['status'] = false;
    	$data = $request->pure();
    	$data['code'] 		  = orderCode($request->type,$request->user_id);
    	
    	
    	$data['shop_id']      = (int)$request->shop_id;
    	$data['openid']       = $request->user->openid;
    	
    	if($request->address_id) {
    	   $userAddress      = UserAddressRepo::find(['id'=>$data['address_id']]);
           $data['address']  = $userAddress->full_address;    		
    	}

        if($request->user_coupon_id) {    
            $couponWhere['id']      = $request->user_coupon_id;
            $couponWhere['is_used'] = 0;      
            $uc = UserCouponRepo::find($couponWhere);
            if($uc){
                // 订单金额不能小于优惠券的满减金额
                if($request->total_amount<object_get($uc,'coupon.min_amount')){
                    $rs['msg'] = '订单金额与优惠券不匹配';
                    return response()->json($rs);
                }
                $data['coupon'] = object_get($uc,'coupon.name');
            } else {
                $rs['msg'] = '优惠券不可用';
                return response()->json($rs);
            }
            
        }
    	
    	$data['status'] = 1;
    	// 传过来 产品id和数量
    	$products = array_pull($data,'products');
    	
    	$ret = OrderRepo::create($data,$products);
    	if($ret) {
    		$rs['status'] = true;
    		$rs['data']   = $ret;
    	}
    	return response()->json($rs);
    }

    

   
}
